<?php

namespace app\modules\group\service;

use Yii;
use app\common\base\CommonService;
use app\modules\group\models\GroupUser;
use app\helpers\DatetimeHelper;

class GroupUserService extends CommonService
{
    function __construct()
    {
        // 对父类service(component)初始化，并指定model
        parent::init();
        $this->model = new GroupUser();
    }

    /**
     * 添加用户
     * @param userId 用户id
	 * @param groupId 用户所属群组
     */
    public function addUser($groupId, $userId)
    {
        $info = $this->info([
			'condition' => [
				'groupId' => $groupId,
                'userId' => $userId,
            ],
            'orderby' => [
                'groupId' => 0,
                'userId' => 1
            ]
		]);

        if (!empty($info)) {
			// @see config/response_code
			return parent::error('ERROR_USER_EXIST_IN_GROUP', '用户已经在群组中');
		}

        $this->model->groupId = $groupId;
        $this->model->userId = $userId;
		$this->model->join_timestamp = DatetimeHelper::msectime();
		$this->model->save();

        return [
			'success' => 1,
		];
    }

    /**
     * 删除用户
     * @param userId 用户id
     */
    public function dropUser($groupId, $userId)
    {
        $info = $this->info([
            'condition' => [
                'groupId' => $groupId,
                'userId' => $userId,
            ],
            'orderby' => [
                'groupId' => 0,
                'userId' => 1
            ]
        ]);

        if (empty($info)) {
            // @see config/response_code
            return parent::error('ERROR_USER_NOT_IN_GROUP', '用户不在群组中');
        }
        
        $this->delete([
            'groupId' => $groupId,
            'userId' => $userId,
        ]);

		return [
			'success' => 1
		];
    }
}